<!DOCTYPE html>
<html lang="zxx" class="no-js">

<head>
	<!-- Mobile Specific Meta -->
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<!-- Favicon-->
	<link rel="shortcut icon" href="img/fav.png">
	<!-- Author Meta -->
	<meta name="author" content="codepixer">
	<!-- Meta Description -->
	<meta name="description" content="">
	<!-- Meta Keyword -->
	<meta name="keywords" content="">
	<!-- meta character set -->
	<meta charset="UTF-8">
	<!-- Site Title -->
	<title>Educature Education</title>

	<!--
			CSS
			============================================= -->
	<link rel="stylesheet"  href="/bootstrap-3.3.7/css/bootstrap.min.css"/>
	<link rel="stylesheet"  href="/bootstrap-fileinput-4.5.2/css/fileinput.min.css"/>
	<style type="text/css">
	.krajee-default .file-thumb-progress {
		top: 31px !important;
	}
	.krajee-default .file-thumb-progress .progress, .krajee-default .file-thumb-progress .progress-bar {
	 height: 20px !important;
	}
	</style>
</head>

<body>
       
   <div class="container-fluid">
    <div class="row form-group">
         <label class="col-md-4">图片上传:</label>
         <div class="col-sm-12">
             <input id="input-id" name="file" class="file-loading"  multiple type="file" data-show-caption="true">
         </div>
     </div>
    <div class="row form-group">
	    <div class="file-loading">
		    <input id="input-702" name="kartik-input-702[]" type="file" multiple>
		</div>
    </div>
</div>
    
	<script src="/js/jquery-2.2.4.min.js"></script>
	<script src="/bootstrap-3.3.7/js/bootstrap.min.js"></script>
	<script src="/bootstrap-fileinput-4.5.2/js/fileinput.min.js"></script>
	<script src="/bootstrap-fileinput-4.5.2/js/locales/zh.js"></script>
	
	<script type="text/javascript">
	
	var List = new Array();//定义一个全局变量去接受文件名和id
	var initialPreviewList = new Array(); 
	var initialPreviewConfigList = new Array(); 
	
	 $(function () {
		 	queryListImgs();
		 	//initFileInput2();
		 	var $el1 = $("#input-702");
			$el1.fileinput({
			    uploadUrl: "/insert",
			    language: 'zh', //设置语言
			    uploadAsync: false,
			    showUpload: false, // hide upload button
			    showRemove: false, // hide remove button
			    overwriteInitial: false, // append files to initial preview
			    minFileCount: 1,
			    maxFileCount: 5,
			    initialPreviewAsData: true,
			}).on("filebatchselected", function(event, files) {
			    $el1.fileinput("upload");
			});
		 	
	     // 修改上传文件按钮的文字-根据需求定义
	        $("#input-id").prev("span.hidden-xs").html("上传文件");
	  });
	 
	 function dowloadImg(){
			var url ='/dowloadImg';
			url = encodeURI(url);
		    location.href = url;
		}
	    function initFileInput2() {
	    	$("#input-702").fileinput({
	            theme: 'fa',
	            uploadUrl: "/insert",
	            uploadAsync: false,
	            minFileCount: 2,
	            maxFileCount: 5,
	            overwriteInitial: false,
	            initialPreview: [
	                "http://lorempixel.com/800/460/people/1",
	                "http://lorempixel.com/800/460/people/2"
	            ],
	            initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup
	            initialPreviewFileType: 'image', // image is the default and can be overridden in config below
	            initialPreviewConfig: [
	                {caption: "People-1.jpg", size: 576237, width: "120px", url: "/site/file-delete", key: 1},
	                {caption: "People-2.jpg", size: 932882, width: "120px", url: "/site/file-delete", key: 2}, 
	            ],
	            uploadExtraData: {
	                img_key: "1000",
	                img_keywords: "happy, places",
	            }
	        }).on('filesorted', function(e, params) {
	            console.log('file sorted', e, params);
	        }).on('fileuploaded', function(e, params) {
	            console.log('file uploaded', e, params);
	        });
	    }
	    function initFileInput(ctrlName) {
	        var control = $('#' + ctrlName);
	        control.fileinput({
	            language: 'zh', //设置语言
	            uploadUrl: "/insert", //上传的地址
	            allowedFileExtensions: ['jpg', 'gif', 'png'],//接收的文件后缀
	            //uploadExtraData:{"id": 1, "fileName":'123.mp3'},
	            // bootstrap fileinput涉及多文件上传的时候会请求多次，上传方式由默认的异步故多个图片上传会出现多次请求。
	            // 改为同步是则为一次性请求
	            uploadAsync: false, //默认异步上传     
	            showUpload: true, //是否显示上传按钮
	            showRemove : true, //显示移除按钮
	            showPreview : true, //是否显示预览
	            showCaption: false,//是否显示标题
	            browseClass : "btn btn-primary", // 按钮样式
	            //browseClass: "btn btn-primary", //按钮样式
	            layoutTemplates: {
	            	//actionDelete: '',   // 除去上传预览的缩略图中的删除图标
	            	actionUpload: '',   // 除去上传预览的缩略图中的上传图标
                    actionZoom: '', // 除去上传预览的缩略图中的查看详情预览的缩略图
	            },
	            //dropZoneEnabled: true,//是否显示拖拽区域
	            //minImageWidth: 50, //图片的最小宽度
	            //minImageHeight: 50,//图片的最小高度
	            //maxImageWidth: 1000,//图片的最大宽度
	            //maxImageHeight: 1000,//图片的最大高度
	            //maxFileSize: 50000,//单位为kb，如果为0表示不限制文件大小
	            //minFileCount: 0,
	            maxFileCount: 15, //表示允许同时上传的最大文件个数
	            enctype: 'multipart/form-data',
	            validateInitialCount:true,
	            initialPreviewAsData: true,
	            initialPreview: initialPreviewList,
	            initialPreviewConfig:initialPreviewConfigList,
	            previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
	            msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
	            msgProgress: '加载第 {index} 文件 共 {files} - {name} - {percent}% 完成.',
	        }).on('filepreupload', function(event, data, previewId, index) {     //上传中
	            var form = data.form, files = data.files, extra = data.extra,
	            response = data.response, reader = data.reader;
	            console.log('文件正在上传');
	            console.log(response);
	        }).on("fileuploaded", function (event, data, previewId, index) {    //一个文件上传成功(//异步上传成功后唤起的方法)
	            console.log('异步文件上传成功！'+data.id);
	            console.log(data);
	 
	        }).on("filebatchuploadsuccess",function(event, data, previewId, index){//同步上传成功后唤起的方法
	            console.log("同步图片上传成功!");
	            
	        	// clearFileInput();//清空插件
	            console.log(data.id+'------'+data.response); // 获取后台返回数据
	           // var data = data.response.fileName;  //文件上传成功返回的文件名，可返回自定义文件名
	           // List.push({ FileName: data, KeyID: previewId });
	            
	            
	        }).on('fileerror', function(event, data, msg) {  //一个文件上传失败
	            console.log('文件上传失败！'+data.id);
	            console.log(data);
	        }).on('filesuccessremove', function (event, data, previewId, index) { // filesuccessremove事件：图片上传成功后，点击删除按钮的回调函数
	        	/* for (var i = 0; i < List.length; i++) { 
	        	      if (List[i].KeyID== data) { 
	        	        delete List[i]; 
	        	      } 
	        	   } */
	         }).on('filepredelete', function(event, key, jqXHR, data) {  
                 console.log('Key = ' + key);  
                 console.log(jqXHR);  
                 console.log(data);   
     		});
	    }
	    
	  //里面有一个需要和后台对应上的文件协商名,后台List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("FileUpload") 
	  //  在fileinput.js中查找('file_data')替换为"FileUpload"就OK
	  //清除插件选择的文件,这个很蛋疼，作者并没有明确提供用代码清除选择文件的方法，只能在页面上手动清除，用户上传成功之后还得手动清除，体验很不好，所以看源码研究一下，如此解决
	   function clearFileInput() {
	      $('#input-id').fileinput('clear')
	   }
  
	  function deletImgByName(imgName) {
		  $.post("/deletImgByName", {
				imgName : imgName
			}, function(result) {
				if (result.STATUS == 1) {
					console.log('delete successfully'+result.MSG);
				} else {
					console.log('delete error '+result.MSG);
				}
			});
	  }
	  
	  function queryListImgs() {
		// 注：在 ajax中 初始化 fileinput 是配置参数是不起作用的  需要 先销毁，再初始化
		$("#input-id").fileinput('destroy');
		  $.post("/queryImgs", {}, function(result) {
				if (result.STATUS == 1) {
					console.log('queryImgs successfully'+result.MSG);
					initialPreviewList = result.findFilePaths; 
					var findFiles = result.findFiles;
					for(var i = 0; i<findFiles.length; i++) {
						initialPreviewConfigList.push('{"caption": "'+findFiles[i]+'", "size": "329892", "width": "120px", "key": "'+ i +'"}');
					}
					
					initFileInput("input-id");
				} else {
					initialPreviewList = new Array(); 
					initialPreviewConfigList = new Array();
					console.log('delete error '+result.MSG);
					initFileInput("input-id");
				}
			});
	  }
	</script>
</body>

</html>